from django.shortcuts import redirect
from django.urls import reverse
import re #正则表达式匹配用

class CentosMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        #print("CentosMiddleware")
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        path = request.path
        print(path)

        # 判断管理后台是否登录
        # 定义后台不登录也可直接访问的url列表
        # 判断当前请求url是否以/myadmin开头，也就是说要访问后台，且不是登录页
        urllist = ['/myadmin/login','/myadmin/logout','/myadmin/dologin','/myadmin/verifycode']
        if re.match(r'^/myadmin',path) and (path not in urllist):
            # 判断是否登录
            if 'adminuser' not in request.session:
                return redirect(reverse("myadmin_login"))

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        #print(request.path)

        return response